package curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.retry.RetryUntilElapsed;

import java.util.concurrent.TimeUnit;

public class CuratorConnection {

    public static void main(String[] args) throws Exception {
        // session重连策略
        //3秒后重连一次，只重连1次
        //RetryPolicy retryPolicy = new RetryOneTime(3000);
        // 每3秒重连一次，重连3次
        //RetryPolicy retryPolicy = new RetryNTimes(3,3000);
        //每3秒重连一次，总等待时间超过10秒后停止重连
        //RetryPolicy retryPolicy=new RetryUntilElapsed(10000,3000);
        //步进间隔重连 baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount+ 1)))
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

        CuratorFramework client = CuratorFrameworkFactory.builder()
                // IP地址端口号
                .connectString("192.168.0.201:2181,192.168.0.202:2181,192.168.0.203:2181")
                //// 会话超时时间
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .namespace("create")
                .build();
        client.start();
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {

            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                //System.out.println(client.getZookeeperClient().getZooKeeper().getSessionId());
                try {
                    //System.out.println(client.getZookeeperClient().getZooKeeper().getSessionId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(newState.name());
            }
        });
       while (true){
           TimeUnit.SECONDS.sleep(1);
           System.out.println(client.getZookeeperClient().getZooKeeper().getSessionId());
       }
    }
}
